﻿using App.Metrics;
using FwProject.Metrics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.Extensions.DependencyInjection
{
   public static class MetricsInfluxDbExtensions
    {

        public static IServiceCollection AddMetricsInfluxDb(this IServiceCollection services, IConfigurationRoot _configurationRoot) {

            var Options = _configurationRoot.GetSection("AppMetrics").Get<MetricsInfluxDbOption>();
            if (Options.IsOpen) {
                var metrics = AppMetrics.CreateDefaultBuilder()
                       .Configuration.Configure(
                       options =>
                       {
                           options.AddAppTag(Options.appTag);
                           options.AddEnvTag(Options.envTag);
                       })
                       .Report.ToInfluxDb(
                       options =>
                       {
                           options.InfluxDb.BaseUri = new Uri(Options.ConnectionString);
                           options.InfluxDb.Database = Options.DataBaseName;
                           options.InfluxDb.UserName = Options.Username;
                           options.InfluxDb.Password = Options.Password;
                           options.HttpPolicy.BackoffPeriod = TimeSpan.FromSeconds(30);
                           options.HttpPolicy.FailuresBeforeBackoff = 5;
                           options.HttpPolicy.Timeout = TimeSpan.FromSeconds(10);
                           options.FlushInterval = TimeSpan.FromSeconds(5);
                       })
                       .Build();

                services.AddMetrics(metrics);
                services.AddMetricsReportScheduler();
                services.AddMetricsTrackingMiddleware();
                services.AddMetricsEndpoints();
            }
       
            return services;
        }
    }
}
